<template>
  <div style="display: inline-block;margin-left: 12px">
    <el-button type="primary" size="small" @click="setPermission">设置权限</el-button>
    <el-drawer
        title="权限设置"
        size="400px"
        :destroy-on-close="false"
        :visible.sync="dialogVisible">
      <el-tree
          :data="treeData"
          :props="props"
          ref="tree"
          :default-expand-all="true"
          node-key="id"
          show-checkbox
          :default-checked-keys="defaultCheckKeys"
          @check-change="handleCheckChange">
      </el-tree>
      <div class="btnBox flex-center">
        <el-button type="primary" @click="submitRoleMenus">确 定</el-button>
      </div>
    </el-drawer>
<!--    <el-dialog-->
<!--        title="设置权限"-->
<!--        :visible.sync="dialogVisible"-->
<!--        width="600px">-->
<!--     -->
<!--      <span slot="footer" class="dialog-footer">-->
<!--        <el-button @click="dialogVisible = false">取 消</el-button>-->
<!--        <el-button type="primary" @click="submitRoleMenus">确 定</el-button>-->
<!--      </span>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
function getChecked(list) {
  let checkedList = [];
  function getObj(obj) {
    if (obj.checked) {
      checkedList.push(obj.id);
    }
    if (obj.items) {
      obj.items.forEach((x) => {
        getObj(x);
      });
    }
  }
  list.forEach((y) => {
    getObj(y);
  });
  return checkedList;
}
export default {
  name: "permissitonBtn",
  props:{
    params:{
      default:()=>{}
    }
  },
  methods:{
    getRolesTree() {
      let params = {
        roleId: this.params.id,
      };
      this.$api.queryMenusByRoleId(params).then((res) => {
        this.treeData = res.data.items;
        this.defaultCheckKeys = getChecked(res.data.items);
      });
    },
    setPermission(){
      this.dialogVisible = true
      this.getRolesTree()
    },
    handleCheckChange(data, checked, indeterminate) {
      console.log(data, checked, indeterminate);
    },
    submitRoleMenus(){
      let nodes = this.$refs.tree.getCheckedNodes()
      let params = {
        "menuIds":nodes.map(x=>x.id).join(';'),
        "roleId": this.params.id
      }
      this.$api.submitRoleMenus(params).then(res=>{
        this.$message.success('配置成功')
        this.dialogVisible = false
      })
    },
  },
  data(){
    return {
      dialogVisible:false,
      props: {
        label: 'title',
        children: 'items'
      },
      defaultCheckKeys:[],
      treeData:[],
    }
  }
}
</script>

<style scoped>

</style>